import {
  Injectable,
  CanActivate,
  Logger,
  HttpException,
  HttpStatus,
  ExecutionContext,
} from '@nestjs/common';
// import * as jwt from 'jsonwebtoken';
import { InjectConfig, ConfigService } from 'nestjs-config';
// import { getUrlQuery } from '@src/utils';
// import { AuthService } from '@src/service/auth/auth.service';
import { Request, Response } from 'express';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from '../entity';
import { Repository, EntityRepository } from 'typeorm';
// import queryString = require("querystring");

@Injectable()
export class AuthGuard implements CanActivate {
  constructor (
    // @InjectConfig() private readonly configService: ConfigService,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>
  ) { }
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();

    // if (this.hasUrl(request.url)) { return true; }

    const token = request.body.token;
    const userId = request.body.userId;
    const result = await this.userRepository.findOne({ userId, token });

    if (result) { return true; }
    return false;
  }

  private hasUrl(url: string): boolean {
    let flag = false;
    const urlList = ['/user/'];
    for (const item of urlList) {
      if (Object.is(item.replace(/\//gi, ''), url.replace(/\//gi, ''))) {
        flag = true;
      }
    }
    return flag;
  }
}
